// 影片展示
let totalMovies = 0; // 总电影数
$(document).ready(function() {
    let currentPage = 1;
    let pageSize = 12;

    loadMovies(currentPage, pageSize); // 默认加载第1页，每页12条数据

    // 绑定筛选按钮点击事件
    $("#apply-filters").click(function() {
        currentPage = 1; // 重置到第一页
        loadMovies(currentPage, pageSize);
    });

    // 绑定分页输入框更新事件
    $("#page-number, #page-size").change(function() {
        const page = parseInt($("#page-number").val());
        const size = parseInt($("#page-size").val());
        currentPage = isNaN(page) ? 1 : page;
        pageSize = isNaN(size) ? 12 : size;
        loadMovies(currentPage, pageSize);
    });

    // 绑定分页按钮点击事件
    $("#pagination").on("click", "button.page-btn", function() {
        currentPage = $(this).data("page");
        loadMovies(currentPage, pageSize);
    });

    // 绑定上一页和下一页按钮点击事件
    $("#pagination").on("click", "button.prev-btn", function() {
        if (currentPage > 1) {
            currentPage--;
            loadMovies(currentPage, pageSize);
        }
    });

    $("#pagination").on("click", "button.next-btn", function() {
        const totalPages = Math.ceil(totalMovies / pageSize);
        if (currentPage < totalPages) {
            currentPage++;
            loadMovies(currentPage, pageSize);
        }
    });

    function loadMovies(page, size) {
        const type = $("input[name='type']:checked").val() || ""; // 获取选中的类型
        const region = $("input[name='region']:checked").val() || ""; // 获取选中的地区

        $.ajax({
            url: `/movies/search`,
            type: "GET",
            data: {
                page: page,
                size: size,
                type: type === "全部" ? "" : type, // 若是“全部”，则改为空字符串
                region: region === "全部" ? "" : region // 若是“全部”，则改为空字符串
            },
            dataType: "json",
            success: function(response) {
                // 获取总数据条数，并传递给setupPagination函数
                totalMovies = response.data.total;
                displayMovies(response.data.records, page, size);
            },
            error: function(xhr, status, error) {
                console.error("Failed to fetch movies:", error);
            }
        });
    }

    function displayMovies(movies, currentPage, pageSize) {
        const movieList = $("#movie-list");
        movieList.empty();

        movies.forEach(movie => {
            const movieDiv = $("<div>").addClass("movie").attr("id", movie.cover);
            const imageUrl = `/img/cover/c` + `${movie.cover}.webp`;
            const img = $("<img>").attr("src", imageUrl).attr("alt", movie.title).css({
                "width": "200px",
                "height": "280px",
                "object-fit": "cover",
                "border-radius": "5px"
            });
            movieDiv.append(img);
            movieDiv.append($("<h3>").text(movie.title));
            movieDiv.append($("<p>").text(`类型: ${movie.type}`));
            movieDiv.append($("<p>").text(`地区: ${movie.region}`));
            movieDiv.append($("<p>").text(`演员: ${movie.actors}`));
            movieDiv.append($("<p>").text(movie.vipOnly ? "VIP影片" : "普通影片"));
            movieList.append(movieDiv);
            // 添加点击事件获取并显示视频
            movieDiv.click(function() {
                const movieId = $(this).attr("id"); // 获取电影 ID
                $.ajax({
                    url: `/movies/play/${movieId}`,
                    method: 'GET',
                    success: function(response) {
                        if (response.code === 200 && response.data && response.data.moviePlayer) {
                            const videoUrl = response.data.moviePlayer.videoUrl;
                            // 使用正则表达式匹配 src 属性值
                            const regex = /<iframe.*?src=["'](.+?)["']/;
                            const match = videoUrl.match(regex);
                            var videoSrc = "";
                            if (match && match.length > 1) {
                                videoSrc = match[1]; // 提取视频地址
                            }

                            // 在页面中显示视频
                            // 检查用户是否已经登录
                            var user = JSON.parse(sessionStorage.getItem("user"));
                            if (!user) {
                                // 用户未登录，提示需要登录
                                alert("请登录后观看影片");
                                // 重定向到登录页面
                                window.location.href = "/login";
                                return;
                            }
                            window.location.href = videoSrc;
                        } else {
                            // 用户不是会员，提示需要成为会员
                            alert("该影片为 VIP 影片，您需要成为会员才能观看");
                            // 重定向到会员注册页面
                            // window.location.href = "/membership";
                        }
                    },
                    error: function() {
                        alert("请求失败，请稍后重试");
                    }
                });
            });
        });

        // 渲染分页按钮
        setupPagination(totalMovies, currentPage, pageSize);
    }
});

//主创作品
$(document).ready(function() {
    // 绑定搜索按钮点击事件
    $("#search-creator-btn").click(function() {
        loadCreators();
    });

    function loadCreators() {
        const keyword = $("#creator-search-input").val();

        $.ajax({
            url: `/index/searchByActor`,
            type: "GET",
            data: {
                actorName: keyword
            },
            dataType: "json",
            success: function(response) {
                displayCreators(response);
            },
            error: function(xhr, status, error) {
                console.error("Failed to fetch creators:", error);
            }
        });
    }

    function displayCreators(creators) {
        const movieList = $("#creator-movie-list");
        movieList.empty();

        creators.forEach(movie => {
            const movieDiv = $("<div>").addClass("movie").attr("id", movie.cover);
            const imageUrl = `/img/cover/c` + `${movie.cover}.webp`;
            const img = $("<img>").attr("src", imageUrl).attr("alt", movie.title).css({
                "width": "200px",
                "height": "280px",
                "object-fit": "cover",
                "border-radius": "5px"
            });
            movieDiv.append(img);
            movieDiv.append($("<h3>").text(movie.title));
            movieDiv.append($("<p>").text(`类型: ${movie.type}`));
            movieDiv.append($("<p>").text(`地区: ${movie.region}`));
            movieDiv.append($("<p>").text(`演员: ${movie.actors}`));
            movieDiv.append($("<p>").text(movie.vipOnly ? "VIP影片" : "普通影片"));
            // 添加点击事件获取并显示视频
            movieDiv.click(function() {
                const movieId = $(this).attr("id"); // 获取电影 ID
                $.ajax({
                    url: `/movies/play/${movieId}`,
                    method: 'GET',
                    success: function(response) {
                        if (response.code === 200 && response.data && response.data.moviePlayer) {
                            const videoUrl = response.data.moviePlayer.videoUrl;
                            // 使用正则表达式匹配 src 属性值
                            const regex = /<iframe.*?src=["'](.+?)["']/;
                            const match = videoUrl.match(regex);
                            var videoSrc = "";
                            if (match && match.length > 1) {
                                videoSrc = match[1]; // 提取视频地址
                            }

                            // 在页面中显示视频
                            // 检查用户是否已经登录
                            var user = JSON.parse(sessionStorage.getItem("user"));
                            if (!user) {
                                // 用户未登录，提示需要登录
                                alert("请登录后观看影片");
                                // 重定向到登录页面
                                window.location.href = "/login";
                                return;
                            }
                            window.location.href = videoSrc;
                        } else {
                            // 用户不是会员，提示需要成为会员
                            alert("该影片为 VIP 影片，您需要成为会员才能观看");
                            // 重定向到会员注册页面
                            // window.location.href = "/membership";
                        }
                    },
                    error: function() {
                        alert("请求失败，请稍后重试");
                    }
                });
            });
            movieList.append(movieDiv);
        });
    }
});